<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :modal-style="{ maxWidth: '1200px' }"
    width="90%"
    @before-ok="save"
    @close="reset"
  >
    <a-form ref="formRef" :model="form" :rules="rules" label-width="60px">
      <a-form-item label="模板名称" field="name">
        <a-input
          v-model.trim="form.name"
          placeholder="请输入模板名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="计费方式" field="type">
        <a-radio-group
          v-model="form.type"
          type="button"
          :disabled="isUpdate"
          handle-item-click
          @change="onChangeType(form.type)"
        >
          <a-radio :value="1">按件数</a-radio>
          <a-radio :value="2">按重量</a-radio>
          <a-radio :value="3">按体积</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="配送区域及运费" field="region">
        <a-table row-key="id" :data="form.region" :pagination="false">
          <template #columns>
            <a-table-column
              title="可配送区域"
              data-index="cityIds"
              :min-width="180"
            >
              <template #cell="{ record, rowIndex }">
                <span v-if="rowIndex === 0">默认全国</span>

                <a-cascader
                  v-else
                  v-model="record.cityIds"
                  path-mode
                  placeholder="请选择地区"
                  :options="cityList"
                  :load-more="loadMore"
                  @change="changeRegion"
                  :fallback="fallback"
                  multiple
                  :field-names="{ label: 'name', value: 'cityId' }"
                ></a-cascader>
              </template>
            </a-table-column>

            <a-table-column
              :title="columns.title"
              dataIndex="first"
              align="center"
            >
              <template #cell="{ record, rowIndex }">
                <a-form-item
                  :rules="rules.first"
                  :field="'region.' + rowIndex + '.first'"
                >
                  <a-input-number
                    v-model="record.first"
                    :step="form.type === 1 ? 1 : 0.1"
                    :min="form.type === 1 ? 1 : 0.1"
                  />
                </a-form-item>
              </template>
            </a-table-column>

            <a-table-column
              title="运费（元）"
              dataIndex="firstPrice"
              align="center"
            >
              <template #cell="{ record, rowIndex }">
                <a-form-item
                  :rules="rules.firstPrice"
                  :field="'region.' + rowIndex + '.firstPrice'"
                >
                  <a-input-number v-model="record.firstPrice" :min="0" />
                </a-form-item>
              </template>
            </a-table-column>

            <a-table-column
              :title="columns.title2"
              dataIndex="renewal"
              align="center"
            >
              <template #cell="{ record, rowIndex }">
                <a-form-item
                  :rules="rules.renewal"
                  :field="'region.' + rowIndex + '.renewal'"
                >
                  <a-input-number
                    v-model="record.renewal"
                    :step="form.type === 1 ? 1 : 0.1"
                    :min="form.type === 1 ? 1 : 0.1"
                  />
                </a-form-item>
              </template>
            </a-table-column>

            <a-table-column
              title="续费（元）"
              dataIndex="renewalPrice"
              align="center"
              class="status-col"
            >
              <template #cell="{ record, rowIndex }">
                <a-form-item
                  :rules="rules.renewalPrice"
                  :field="'region.' + rowIndex + '.renewalPrice'"
                >
                  <a-input-number v-model="record.renewalPrice" :min="0" />
                </a-form-item>
              </template>
            </a-table-column>

            <a-table-column title="操作" align="center" :width="150">
              <template #cell="{ record, rowIndex }">
                <a-button
                  v-if="rowIndex > 0"
                  type="text"
                  size="small"
                  @click="confirmEdit(form.region, rowIndex)"
                >
                  删除
                </a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          size="small"
          icon="icon-edit"
          @click="addRegion(form.region)"
        >
          添加配送区域
        </a-button>
      </a-form-item>
      <a-form-item label="指定包邮" field="appoint">
        <a-radio-group v-model="form.appoint">
          <a-radio :value="true">开启</a-radio>
          <a-radio :value="false">关闭</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.appoint === true" field="free">
        <a-table row-key="id" :data="form.free" :pagination="false">
          <template #columns>
            <a-table-column title="选择地区" align="center">
              <template #cell="{ record }">
                <a-cascader
                  style="width: 95%"
                  path-mode
                  v-model="record.cityIds"
                  placeholder="请选择地区"
                  :options="cityList"
                  :fallback="fallback"
                  :load-more="loadMore"
                  @change="changeRegion"
                  multiple
                  :field-names="{ label: 'name', value: 'cityId' }"
                />
              </template>
            </a-table-column>
            <a-table-column :title="columns.title3" align="center">
              <template #cell="{ record }">
                <a-input-number
                  v-model="record.number"
                  :step="form.type === 1 ? 1 : 0.1"
                  :min="form.type === 1 ? 1 : 0.1"
                />
              </template>
            </a-table-column>
            <a-table-column title="包邮金额（元）" align="center">
              <template #cell="{ record }">
                <a-input-number v-model="record.price" />
              </template>
            </a-table-column>
            <a-table-column title="操作" align="center">
              <template #cell="{ record, rowIndex }">
                <a-button
                  type="text"
                  size="small"
                  @click="confirmEdit(form.free, rowIndex)"
                >
                  删除
                </a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-form-item>
      <a-form-item v-if="form.appoint === true">
        <a-button
          type="primary"
          size="small"
          icon="icon-edit"
          @click="addFree(form.free)"
        >
          添加指定包邮区域
        </a-button>
      </a-form-item>
      <a-form-item label="排序" field="sort">
        <a-input-number
          v-model="form.sort"
          placeholder="请输入菜单排序"
          :min="1"
          mode="button"
          style="width: 150px"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { type FormInstance, Message } from "@arco-design/web-vue";
import {
  addShippingTemplates,
  getShippingTemplates,
  getSystemCityTreeChild,
  getSystemCityTreeTop,
  updateShippingTemplates,
  listShippingTemplatesFree,
  listShippingTemplatesRegion,
  getAllDescendants
} from "@/apis";

import { getItem, setItem } from "@/utils/sessionStorage";

import { useForm } from "@/hooks";

const emit = defineEmits<{
  (e: "save-success"): void;
}>();

const dataId = ref("");
const isUpdate = computed(() => !!dataId.value);
const title = computed(() =>
  isUpdate.value ? "修改运费模板" : "新增运费模板"
);
const formRef = ref<FormInstance>();

const rules: FormInstance["rules"] = {
  name: [{ required: true, message: "请输入模板名称" }],
  type: [{ required: true, message: "请输入包邮方式" }],
  // free: [{ type: "array", required: true, message: "请至少添加一个地区" }],
  // appoint: [{ required: true, message: "请选择是否指定包邮" }],
  // undelivery: [{ required: true, message: "请选择是否指定区域不配送" }],
  // region: [{required: true,message: "请选择活动区域",}],
  // first: [{ required: true, message: "请输入" }],
  // renewal: [{ required: true, message: "请输入" }],
  // firstPrice: [{ required: true, message: "请输入运费" }],
  // renewalPrice: [{ required: true, message: "请输入续费" }],
  // cityId3: [{ type: "array", required: true, message: "请至少选择一个地区" }],
};

const { form, resetForm } = useForm({
  name: "",
  type: 1,
  appoint: false,
  sort: 0,
  region: [
    {
      first: 0,
      firstPrice: 0,
      renewal: 0,
      renewalPrice: 0,
      cityIds: [],
    },
  ],
  undelivery: 0,
  free: [],
  undelives: {},
  cityId3: [],
});

// 重置
const reset = () => {
  formRef.value?.resetFields();
  resetForm();
};

const visible = ref(false);

const cityList = ref([]);
onMounted(() => {
  const cityListFromStorage = getItem("cityList", []);
  if (cityListFromStorage && cityListFromStorage.length > 0) {
    cityList.value = cityListFromStorage;
  } else {
    getCityList();
  }
});

const fallback = (value) => {
  return getProvinceCityDistrictNames(value)
}

const findCityNameById = (cityList, cityId) => {
  for (const city of cityList) {
    if (city.cityId === cityId) {
      return city.name;
    }
    if (city.child && city.child.length > 0) {
      const name = findCityNameById(city.child, cityId);
      if (name) {
        return name;
      }
    }
  }
  return null;
};

const getProvinceCityDistrictNames = (cityIdArray) => {
  const names = cityIdArray.map(cityId => findCityNameById(cityList.value, cityId));
  return names.filter(name => name).join('/');
};

const getCityChild = async (id) => {
  const res = await getSystemCityTreeChild(id);
  return res.data;
};

const getCityAllDescendants = async (id) => {
  const res = await getAllDescendants(id);
  return res.data;
};

const getCityList = async () => {
  const res = await getSystemCityTreeTop();
  cityList.value = res.data;

  // const node = await getCityAllDescendants(option.cityId);

  setItem("cityList", res.data);
};


const loadMore = async (option, done) => {
  // 从 sessionStorage 获取 cityList
  const storedCityList = getItem("cityList",[]);
  // 递归查找并更新顶层节点
  const updateCityList = (cityList, cityId, childNodes) => {
    for (const city of cityList) {
      if (city.cityId === cityId) {
        // 找到顶层节点，更新其 child 和 children 属性
        city.child = childNodes;
        city.children = childNodes;
        return true; // 找到后返回 true，避免继续递归
      }
      if (city.child && city.child.length > 0) {
        // 如果有子节点，递归查找并更新
        const updated = updateCityList(city.child, cityId, childNodes);
        if (updated) return true; // 如果已经更新，停止递归
      }
    }
    return false;
  };

  // // 查找对应的顶层节点
  const topLevelNode = storedCityList.find(city => city.cityId === option.cityId);

  // if (topLevelNode && (topLevelNode.child || topLevelNode.children)) {
  //   // 如果顶层节点已经有 child 或 children，则直接使用，不再调用接口
  //   done(topLevelNode.children || topLevelNode.child);
  //   return;
  // }

  // 获取省下的所有市和区节点
  const node = await getCityAllDescendants(option.cityId);

  if (!node || node.length === 0) {
    option.isLeaf = true;
    done([]);
    return;
  }

  // 遍历获取的市节点并设置区的 isLeaf 为 true
  node.map(city => {
    if (city.child && city.child.length > 0) {
      city.child.map(district => {
        district.isLeaf = true;
        return district;
      });
    }
    city.children = city.child;
    return city;
  });

  // 更新顶层节点的 child 和 children
  if (topLevelNode) {
    topLevelNode.child = node;
    topLevelNode.children = node;
  }

  // 更新 cityList 中对应的顶层节点
  updateCityList(storedCityList, option.cityId, node);

  // 更新 cityList 并保存到 sessionStorage
  setItem("cityList", storedCityList);

  // 标记加载完成并传递节点数据
  done(node);
};

const confirmEdit = (row, rowIndex) => {
  row.splice(rowIndex, 1);
};

// 添加配送区域
const addRegion = (region) => {
  region.push(
    Object.assign(
      {},
      {
        first: 0,
        firstPrice: 0,
        renewal: 0,
        renewalPrice: 0,
        cityIds: [],
      }
    )
  );
};

const addFree = (free) => {
  free.push(
    Object.assign(
      {},
      {
        number: 1,
        price: 1,
        cityIds: [],
      }
    )
  );
};

// 新增
const onAdd = () => {
  reset();
  dataId.value = "";
  visible.value = true;
};

const kg = "重量（kg）";
const m = "体积（m³）";
const statusMap = [
  {
    title: "首件",
    title2: "续件",
    title3: "包邮件数",
  },
  {
    title: `首件${kg}`,
    title2: `续件${kg}`,
    title3: `包邮${kg}`,
  },
  {
    title: `首件${m}`,
    title2: `续件${m}`,
    title3: `包邮${m}`,
  },
];

const changeRegion = (value) => {
  console.log(value);
};

const columns = ref({
  title: "首件",
  title2: "续件",
  title3: "包邮件数",
});
// 切换类型清除校验
const onChangeType = (num) => {
  formRef.value?.clearValidate();
  columns.value = Object.assign({}, statusMap[num - 1]);
  console.log(columns);
};

// 修改
const onUpdate = async (id: string) => {
  reset();
  dataId.value = id;
  const res = await getShippingTemplates(id);
  Object.assign(form, res.data);
  const region = await shippingRegion(id);
  const free =await shippingFree(id);
  form.region = region;
  form.free = free;
  visible.value = true;
};

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.validate();
    if (isInvalid) return false;
    const param = {
      appoint: form.appoint,
      name: form.name,
      sort: form.sort,
      type: form.type,
      shippingTemplatesRegionRequestList: [],
      shippingTemplatesFreeRequestList: [],
    };

    form.region.forEach((el: any) => {
      el.title = el.cityIds.length > 0
          ? JSON.stringify(el.cityIds)
          : JSON.stringify([[0, 0]]);
      for (var i = 0; i < el.cityIds.length; i++) {
        el.cityIds[i].shift()
      }
      el.cityId = el.cityIds.length > 0 ? el.cityIds.join(",") : "all";
    });

    param.shippingTemplatesRegionRequestList = form.region.map((el: any) => ({
      ...el,
      // Remove unnecessary properties if needed
      // city_ids: undefined,
      // city_id: undefined,
    }));

    if (form.appoint) {
      form.free.forEach((el: any) => {
        el.title =
          el.cityIds.length > 0
            ? JSON.stringify(el.cityIds)
            : JSON.stringify([[0, 0]]);
        for (var i = 0; i < el.cityIds.length; i++) {
          el.cityIds[i].shift()
        }

        el.cityId = el.cityIds.length > 0 ? el.cityIds.join(",") : "all";
      });
    }

    param.shippingTemplatesFreeRequestList = form.free.map((el: any) => ({
      ...el,
      // Remove unnecessary properties if needed
      // city_ids: undefined,
      // city_id: undefined,
    }));

    if (isUpdate.value) {
      await updateShippingTemplates(param, dataId.value);
      Message.success("修改成功");
    } else {
      await addShippingTemplates(param);
      Message.success("新增成功");
    }
    emit("save-success");
    return true;
  } catch (error) {
    console.error(error);
    return false;
  }
};

// 不包邮
const shippingRegion = async (tempId:string) => {
  const res = await listShippingTemplatesRegion(tempId);
  res.data.map((item, index) => {
    item.title = JSON.parse(item.title)
    item.cityIds = item.title
  })
  return res.data
};

// 包邮
const shippingFree = async (tempId:string) => {
  const res = await listShippingTemplatesFree(tempId);
  res.data.map((item, index) => {
    item.title = JSON.parse(item.title)
    item.cityIds = item.title
  })
  return res.data
};   

defineExpose({ onAdd, onUpdate });
</script>
